package com.xinwei.utils;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.xinwei.constant.Status;
import com.xinwei.constant.StringConstant;
import com.xinwei.constant.TimeConstant;
import com.xinwei.excpetion.ManagerException;
import com.xinwei.excpetion.ManagerExceptionEnmu;
import org.springframework.boot.autoconfigure.security.oauth2.resource.OAuth2ResourceServerProperties;

import java.util.Date;

public class JWTUtils {

    /**
     * 生成token
     */
    public static String getToken() {
        Date data = new Date(System.currentTimeMillis() + TimeConstant.EXPIRE_TIME);
        String token = JWT.create()
                .withIssuer("xinwei")
                .withExpiresAt(data)
                .sign(Algorithm.HMAC256(StringConstant.TOKEN_SECRET));
        return token;
    }

    /**
     * 验证token
     */
    public static void verify(String token) {
        try {
            JWT.require(Algorithm.HMAC256(StringConstant.TOKEN_SECRET)).withIssuer("xinwei").build().verify(token);
        } catch (JWTVerificationException e) {
            throw new ManagerException(ManagerExceptionEnmu.ERROR_TOKEN);
        }
    }

}
